package com.itheima.order.controller;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//编写切面类
@Aspect
@Component
public class IdempotentAspect {

    @Autowired
    RedisTemplate redisTemplate;

    @Pointcut(value = "@annotation(com.itheima.annotation.IdempotentDemo)")
    public void access(){
    }

    @Before("access()")
    public void deBefore(JoinPoint joinPoint) throws Throwable {
        System.out.println("second before");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String token = request.getHeader("token");
        Boolean flag = checkToken(token);
        if (!flag){
            throw new RuntimeException("请重试....");
        }
    }

    private Boolean checkToken(String token){

        if (token==null){
            System.out.println("没有传递token");
            return false;
        }

        Long increment = redisTemplate.opsForValue().increment(token);
        if (increment==1){
            System.out.println("token校验通过");
            return true;
        }else {
            System.out.println("校验失败");
            return false;

        }
    }

}
